package agent;

import bytecode.Test;
import javassist.*;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class PreMainTraceAgentJavassist {
    public static void agentmain(String agentArgs, Instrumentation ins) {
        ins.addTransformer(new PreMainTraceAgentJavassist.DefineTransformer(), true);
        //重定义类并载入新的字节码
        try {
            ins.retransformClasses(Test.class);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static class DefineTransformer implements ClassFileTransformer {
        @Override
        public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
            System.out.println("Transforming:"+className);
            try {
                CtClass ctClass = this.adivceTest();
                return ctClass.toBytecode();
            }catch (Exception e){
                e.printStackTrace();
            }

            return classfileBuffer;
        }

        public CtClass adivceTest() throws NotFoundException, CannotCompileException, InstantiationException, IllegalAccessException {
            ClassPool pool = ClassPool.getDefault();
            CtClass ctClass = pool.get("bytecode.Test");
            CtMethod m = ctClass.getDeclaredMethod("process");
            m.insertBefore("{ System.out.println(\"start\"); }");
            m.insertAfter("{ System.out.println(\"end\"); }");
//            Class c = ctClass.toClass();
//            Test h = (Test) c.newInstance();
//            h.process();
            return ctClass;
        }
    }
}
